<template>
  <div class="user-container">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="用户名">
          <el-input v-model="queryParams.username" placeholder="请输入用户名" style="width: 240px" clearable/>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="queryParams.nickname" placeholder="请输入昵称" style="width: 240px" clearable/>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px">
            <el-option label="正常" :value="1"/>
            <el-option label="禁用" :value="0"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <el-card class="table-card">
      <template #header>
        <el-button type="primary" @click="handleAdd">新增用户</el-button>
      </template>

      <!-- 表格 -->
      <el-table :data="userList" border>
        <el-table-column type="index" label="序号" width="50"/>
        <el-table-column prop="username" label="用户名"/>
        <el-table-column prop="nickname" label="昵称"/>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"/>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="primary" link @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="primary" link @click="handleReset(scope.row)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.current"
          v-model:page-size="  queryParams.size"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="dialogType === 'edit'"/>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname"/>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" type="password" show-password/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :value="1" label="正常">正常</el-radio>
            <el-radio :value="0" label="禁用">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { request } from '@/utils/request'

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 10,
  username: '',
  nickname: '',
  status: ''
})

const total = ref(0)
const userList = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add')
const dialogTitle = ref('新增用户')
const userFormRef = ref(null)

// 表单相关
const userForm = ref({})

// 默认表单数据
const defaultForm = {
  username: '',
  nickname: '',
  password: '',
  status: 1
}

// 初始化表单数据
const initForm = () => {
  userForm.value = { ...defaultForm }
}

const userRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

// 获取用户列表
const getList = async () => {
  try {
    const res = await request('/api/user/list', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(queryParams)
    })
    if (res.code === 200) {
      userList.value = res.data.records
      total.value = Number(res.data.total)
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

// 查询
const handleQuery = () => {
  queryParams.current = 1
    queryParams.size = 10
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.username = ''
  queryParams.nickname = ''
  queryParams.status = ''
  queryParams.current = 1
    queryParams.size = 10
  getList()
}

// 新增用户
const handleAdd = () => {
  dialogType.value = 'add'
  dialogTitle.value = '新增用户'
  initForm()
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  dialogTitle.value = '编辑用户'
  try {
    // 获取最新的用户数据
    const res = await request(`/api/user/get?id=${row.id.toString()}`, {
      method: 'GET'
    })
    if (res.code === 200) {
      userForm.value = {
        id: res.data.id.toString(),
        username: res.data.username,
        nickname: res.data.nickname,
        status: res.data.status
      }
      dialogVisible.value = true
    }
  } catch (error) {
    console.error('获取用户详情失败:', error)
    ElMessage.error('获取用户详情失败')
  }
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该用户吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const res = await request(`/api/user/delete?id=${row.id.toString()}`, {
        method: 'GET'
      })
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      }
    } catch (error) {
      console.error('删除用户失败:', error)
    }
  })
}

// 重置密码
const handleReset = (row) => {
  ElMessageBox.confirm('确认重置该用户的密码吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const res = await request(`/api/user/reset-password?id=${row.id.toString()}`, {
        method: 'GET'
      })
      if (res.code === 200) {
        ElMessage.success('重置密码成功')
      }
    } catch (error) {
      console.error('重置密码失败:', error)
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    
    const url = dialogType.value === 'add' ? '/api/user/add' : '/api/user/update'
    
    const res = await request(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(userForm.value)
    })
    
    if (res.code === 200) {
      ElMessage.success(dialogType.value === 'add' ? '新增成功' : '修改成功')
      dialogVisible.value = false
      getList()
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败')
  }
}

// 对话框关闭
const handleDialogClose = () => {
  initForm()
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
}

// 分页
const handleSizeChange = (val) => {
    queryParams.size = val
  queryParams.current = 1
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.current = val
  getList()
}

// 初始化
onMounted(() => {
  initForm()
  getList()
})
</script>

<style scoped>
.user-container {
  padding: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.table-card {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 